﻿Imports Global_Visas_Business_Layer
Imports System.Data
Imports System.Text
Imports System.ComponentModel
Partial Public Class frmAddNewCase
    Private _CompanyId As Long
    Private _Loading As Boolean = False

    Public Property CompanyId() As Long
        Get
            Return _CompanyId
        End Get
        Set(ByVal value As Long)
            _CompanyId = value
        End Set
    End Property

    Private Sub frmAddNewCase_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Me.KeyUp
        If e.Key = Key.Escape Then
            btnCancel_Click(sender, e)
        End If
    End Sub

    Private Sub AddNewCase_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loaded

        Dim dtCons As DataTable

        Try
            GeneralTasks.ChangeTheme(Me)
            GeneralTasks.EnumerateandFill(Me.LogicalChildren)
            _Loading = True

            Dim intBranchID = CommonDataFunctions.GetLoggedOnConsultantBranchID

            dtCons = CommonDataFunctions.ConsultantList()
            'If Security._SecurityLevel = SecurityLevel.NormalUser Then
            '    dtCons = CommonDataFunctions.GetLoggedOnConsultantAsList()
            'Else
            '    dtCons = CommonDataFunctions.ConsultantList(, , , intBranchID)
            'End If


            With Me.drpContact
                .SelectedValuePath = "Person_ID"
                .DisplayMemberPath = "PersonName"
                .ItemsSource = CType(Company.CompanyContacts(Me.CompanyId), IListSource).GetList
                .SelectedIndex = -1
            End With


            With Me.drpBranch
                .SelectedValuePath = "Branch_ID"
                .DisplayMemberPath = "Branch_Name"
                .ItemsSource = CType(CommonDataFunctions.BranchList, IListSource).GetList
                .SelectedValue = intBranchID
            End With
            With Me.drpProdType
                .SelectedValuePath = "ProductType_ID"
                .DisplayMemberPath = "Product Type"
                .ItemsSource = CType(Products.ProductTypesList(), IListSource).GetList
                .SelectedIndex = -1
            End With

            With Me.drpConsultant
                .DisplayMemberPath = "con_name"
                .SelectedValuePath = "con_id"
                .ItemsSource = CType(dtCons, IListSource).GetList
                .SelectedIndex = -1
            End With


            With Me.drpCoordinator
                .SelectedValuePath = "con_id"
                .DisplayMemberPath = "con_name"
                .ItemsSource = CType(dtCons, IListSource).GetList
                .SelectedIndex = -1
            End With

            With Me.drpCaseWorker
                .SelectedValuePath = "con_id"
                .DisplayMemberPath = "con_name"
                .ItemsSource = CType(dtCons, IListSource).GetList
                .SelectedIndex = -1
            End With

            If Security._SecurityLevel <> SecurityLevel.AdminUser Then
                Me.drpBranch.IsEnabled = False
            End If

            ' check if a company or private individual
            If Me.CompanyId > 0 Then
                Me.lblCompanyId.Content = Me.CompanyId.ToString
                With Me.drpCandidate
                    .SelectedValuePath = "Person_ID"
                    .DisplayMemberPath = "PersonName"
                    .ItemsSource = CType(Company.CompanyCandidates(Me.CompanyId), IListSource).GetList
                    .SelectedIndex = -1
                End With
            Else
                If Not GlobalCRM.CurrentCandidateName Is Nothing Then
                    With Me.drpCandidate
                        .Items.Add(GlobalCRM.CurrentCandidateName)
                        .SelectedItem = GlobalCRM.CurrentCandidateName
                        .IsEnabled = False
                    End With
                End If
                Me.lblCompany.Visibility = Windows.Visibility.Hidden
                Me.lblCompanyId.Visibility = Windows.Visibility.Hidden
                Me.lblContact.Visibility = Windows.Visibility.Hidden
                Me.drpContact.Visibility = Windows.Visibility.Hidden
            End If
        Catch exc As Exception
            CommonFuncs.ErrorHandler(exc, "frmAddNewCase.LOad", False)
        Finally
            _Loading = False
        End Try
    End Sub

    Private Sub drpProdType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpProdType.SelectionChanged
        Dim listOfProducts As DataTable = Nothing
        If (drpProdType.SelectedValue <> Nothing) Then
            listOfProducts = Products.ProductList(Me.drpProdType.SelectedValue)
        End If
        With Me.drpProduct
            .SelectedValuePath = "Product_ID"
            .DisplayMemberPath = "Product_Name"
            .ItemsSource = CType(listOfProducts, IListSource).GetList
            .SelectedIndex = -1
        End With
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim cmn As New CommonFuncs
        Dim Tsk As New TasksEvents
        Try


            If drpConsultant.SelectedIndex = -1 And _
                drpCaseWorker.SelectedValue = -1 And _
                drpCoordinator.SelectedValue = -1 Then
                CommonFuncs.DisplayMessage("You must select either a Sales Consultant, Case Service Manger or Case Co-Ordinator", CommonDialog.CustomDialogIcons.Information, String.Empty)
                Exit Sub
            End If

            If Me.drpProduct.SelectedIndex = -1 Then
                CommonFuncs.DisplayMessage("You must select a Product", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            If Me.chkInitiated.IsChecked And Me.chkInitiated.Visibility And Me.drpCandidate.SelectedIndex = -1 Then
                CommonFuncs.DisplayMessage("Cannot create a case as initiated without specifying a candidate", CommonDialog.CustomDialogIcons.Information, "Error")
                Me.chkInitiated.Focus()
                Exit Sub
            End If

            Dim myCase As New Cases.CaseInfo

            With myCase
                If Me.chkInitiated.IsChecked And Me.chkInitiated.IsVisible Then
                    .SoldDate = Now
                    .CaseStatusId = 4
                Else
                    .CaseStatusId = 2
                End If
                .CompanyId = Me.CompanyId
                .EnteredBy = GlobalCRM.CurrentConName
                .Contactid = Me.drpContact.SelectedValue
                If Me.CompanyId > 0 Then
                    .CandidateId = Me.drpCandidate.SelectedValue
                Else
                    .CandidateId = GlobalCRM.CurrentCandidateID
                End If

                .Productid = Me.drpProduct.SelectedValue
                .SalesConid = Me.drpConsultant.SelectedValue
                .CaseWorkerId = Me.drpCaseWorker.SelectedValue
                .CaseCoordinatorID = Me.drpCoordinator.SelectedValue
                .StatusChangeDate = Now
            End With

            myCase.CaseId = Cases.CreateNewCase(myCase)

            If myCase.CaseId = 0 Then
                CommonFuncs.DisplayMessage("Error creating new case!", CommonDialog.CustomDialogIcons.Information, "Error")
                Exit Sub
            End If

            ' log event to record new case added
            Tsk.GblFunc_Add_Event("Case Added", "Case " & myCase.CaseId.ToString & " added via CRM.", TasksEvents.EventStatus.SingleEvent, myCase.CaseId, TasksEvents.EventTypes.EventCase)

            Accounts.LoadDefaultCharges(myCase.CaseId)

            'Check for previous initiated cases on this account
            Dim SQL As New StringBuilder
            Dim FirstCase As Integer

            With SQL
                .Append("Select count(*) from D_Case ")
                .Append(" Where Case_ID < " & myCase.CaseId)
                .Append(" And Case_StatusID Between 100 and 1020")

                If Me.CompanyId = 0 Then
                    .Append(" AND case_CandidateId = " & myCase.CandidateId)
                Else
                    .Append(" AND case_CompanyId = " & Me.CompanyId)
                End If

            End With

            If CommonDataFunctions.GetSQLScalar(SQL.ToString) = 0 Then
                FirstCase = 1
            Else
                FirstCase = 0
            End If

            'Add Document requirements

            SQL = New StringBuilder

            With SQL
                .Append("INSERT INTO D_DocReqs")
                .Append(" (DocReq_Name, DocReq_Type, DocReq_TypeID, DocReq_DTEntered, DocReq_EnteredBy, DocReq_CaseID)")
                .Append(" SELECT     DefDocReq_Name, DefDocReq_Type, DefDocReq_TypeID ,GETDATE() AS Entered, '" & cmn.SwapQuotes(GlobalCRM.CurrentConName) & "' AS enteredBy, " & myCase.CaseId & " AS CaseID")
                .Append(" FROM D_DefDocReqs")
                .Append(" Left Outer Join L_DocReqTypes on D_DefDocReqs.DefDocReq_TypeID = DocReqType_ID")
                .Append(" WHERE (DefDocReq_ProductID = " & myCase.Productid & ")")
                .Append(" AND (DocReqType_ClientType IN ")
                If Me.CompanyId = 0 Then
                    .Append(" (0,1))")
                Else
                    .Append(" (0,2))")
                End If
                If FirstCase = 0 Then
                    .Append(" AND (DocReqType_FTO = 0)")
                End If
            End With

            If Not CommonDataFunctions.ExecuteSQL(SQL.ToString) Then
                Exit Sub
            End If
            'code to trigger send email to the client when the new lead is assigned a consultant
            'If myCase.CaseStatusId = 5 Then 'And myCase.EnteredBy = "Web"
            'pick saleconid , mycase info and send to the function to email the client
            'Dim myPerson As People.PersonInfo = People.GetPerson(myCase.CandidateId)
            'CommonFunc.SendEmailToClient(myCase, Nothing, myPerson)
            'End If

            Me.Close()
        Catch ex As Exception
        Finally
            cmn = Nothing
            Tsk = Nothing
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub

    Private Sub drpBranch_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles drpBranch.SelectionChanged
        'Try
        '    drpProdType.ItemsSource = CType(Products.ProductTypeList(drpBranch.SelectedValue, -1, False), IListSource).GetList
        '    If drpProdType.Items.Count > 0 And _Loading = False Then
        '        drpProdType.SelectedIndex = 0
        '    End If
        'Catch ex As Exception
        '    CommonFuncs.ErrorHandler(ex, "frmAddNewCase.drpBranch_SelectedIndexChanged")
        'Finally
        'End Try
    End Sub
End Class
